<!-- src/view/Login.vue -->
<template>
  <div class="login-container">
    <div class="login-form">
      <h2>智能工厂管理系统</h2>
      <el-form ref="loginFormRef" :model="member" :rules="rules" class="login-ruleForm">
        <el-form-item prop="username">
          <el-input
              v-model="member.username"
              placeholder="请输入用户名"
              prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="member.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
                v-model="member.captcha"
                placeholder="请输入验证码"
                prefix-icon="Key"
                style="flex: 1; margin-right: 10px;"
            />
            <img
                v-if="captchaImg"
                :src="captchaImg"
                alt="验证码"
                @click="loadCaptcha"
                class="captcha-img"
                @error="handleImageError"
            />
            <div v-else class="captcha-placeholder">加载中...</div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="onSubmit"
              :loading="loading"
              class="login-button"
          >
            登录
          </el-button>
        </el-form-item>

        <!-- 新增注册按钮 -->
        <el-form-item class="register-link">
          <el-button type="text" @click="goToRegister">
            没有账号？立即注册
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import loginApi from '../api/login_api.js';

const router = useRouter();
const loginFormRef = ref();

// 表单数据
const member = reactive({
  username: '',
  password: '',
  captcha: '',
  key: ''
});

// 验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

// 状态管理
const captchaImg = ref('');
const loading = ref(false);
const isCaptchaLoading = ref(false);

// 图片加载错误处理
const handleImageError = (e) => {
  // 只有在确实有图片但加载失败时才提示错误
  if (captchaImg.value) {
    console.error('验证码图片加载失败:', e);
    console.log('当前captchaImg值:', captchaImg.value);
    // 不再显示错误消息，因为图片可能已经成功显示
    // ElMessage.error('验证码图片加载失败');
  }
};

// 清理Base64字符串中的非法字符
function cleanBase64String(base64Str) {
  if (!base64Str) return base64Str;
  return base64Str.replace(/[^A-Za-z0-9+/=]/g, '');
}

// 验证Base64字符串的合法性
function isValidBase64(str) {
  if (typeof str !== 'string') return false;
  const base64Regex = /^[A-Za-z0-9+/]*={0,2}$/;
  return base64Regex.test(str);
}

// 加载验证码
const loadCaptcha = async () => {
  isCaptchaLoading.value = true;
  try {
    const res = await loginApi.captcha();
    console.log('验证码响应:', res);

    if (res && res.code === 200) {
      if (!res.data) {
        console.error('验证码数据为空');
        ElMessage.error('验证码数据异常：服务器未返回有效数据');
        return;
      }

      let base64Data = null;
      let keyData = null;

      if (res.data.base64 && res.data.key) {
        base64Data = res.data.base64;
        keyData = res.data.key;
      } else if (res.data.data && res.data.data.base64 && res.data.data.key) {
        base64Data = res.data.data.base64;
        keyData = res.data.data.key;
      }

      if (base64Data && keyData) {
        const cleanedBase64Data = cleanBase64String(base64Data);
        if (isValidBase64(cleanedBase64Data)) {
          captchaImg.value = 'data:image/png;base64,' + cleanedBase64Data;
          member.key = keyData;
          console.log('验证码加载成功');
        } else {
          console.error('非法的Base64字符串:', cleanedBase64Data);
          ElMessage.error('验证码数据异常：Base64格式错误');
        }
      } else {
        console.error('验证码数据结构不正确:', res.data);
        ElMessage.error('验证码数据异常：数据结构不正确');
      }
    } else {
      const errorMsg = res?.msg || '获取验证码失败';
      console.error('获取验证码失败:', errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (err) {
    console.error('获取验证码异常:', err);
    ElMessage.error('获取验证码异常: ' + (err.message || '请检查网络连接'));
  } finally {
    isCaptchaLoading.value = false;
  }
};

// 登录提交
const onSubmit = async () => {
  if (!member.username || !member.password || !member.captcha) {
    ElMessage.warning('请填写完整信息');
    return;
  }

  loading.value = true;

  try {
    const loginData = {
      username: member.username,
      password: member.password,
      captcha: member.captcha,
      key: member.key
    };

    console.log('发送登录请求数据:', loginData);

    const res = await loginApi.dologin(loginData);
    console.log('登录响应:', res);

    if (res && res.code === 200) {
      const token = res.data?.token || res.data || 'success';
      if (token) {
        localStorage.setItem("token", token);
        const userInfo = { name: member.username };
        localStorage.setItem("userInfo", JSON.stringify(userInfo));

        ElMessage.success('登录成功');
        router.replace('/');
      } else {
        ElMessage.error('登录响应中未包含有效token');
      }
    } else {
      ElMessage.error(res?.msg || '登录失败');
      loadCaptcha();
    }
  } catch (err) {
    console.error('登录异常', err);
    ElMessage.error('登录异常: ' + (err.message || '请检查网络连接'));
    loadCaptcha();
  } finally {
    loading.value = false;
  }
};

// 跳转注册页
const goToRegister = () => {
  router.push('/register');
};

// 组件挂载时加载验证码
onMounted(() => {
  loadCaptcha();
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  width: 400px;
  padding: 40px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  text-align: center;
}

.login-form h2 {
  margin-bottom: 30px;
  color: #333;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-img {
  height: 40px;
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  display: block;
}

.captcha-placeholder {
  height: 40px;
  line-height: 40px;
  width: 100px;
  text-align: center;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #999;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 10px;
}
</style>